﻿using System;
using UnityEngine;
using System.Collections;
using JetBrains.Annotations;
using Object = UnityEngine.Object;

namespace UnityExtensions
{
	public static class GameObjectUtility
	{
		/// <summary>
		/// 取得当前对象的某个组件 如果不存在 就添加!
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="ojb"></param>
		/// <param name="self"></param>
		/// <returns>如果ojb为null就返回null</returns>
		public static T GetComponentOrAdd<T>([NotNull] this GameObject self) where T : Component
		{
			if (self == null) throw new ArgumentNullException("self");
			var t = self.GetComponent<T>();
			if (t.IsRefNull())
			{
				t = self.AddComponent<T>();
			}
			return t;
		}
		public static GameObject FindChild(this GameObject self, string childname)
		{
			var child = self.transform.Find(childname);
			return child == null ? null : child.gameObject;
		}
		/// <summary>
		/// 查找名为name的GameObject,如果没有new一个
		/// </summary>
		/// <param name="name"></param>
		/// <param name="dontDestroyOnLoad"></param>
		/// <returns></returns>
		public static GameObject FindOrNew(string name, bool dontDestroyOnLoad = true)
		{
			var gobj = GameObject.Find(name);
			if (gobj != null) return gobj;

			gobj = new GameObject(name);
			if (dontDestroyOnLoad)
			{
				Object.DontDestroyOnLoad(gobj);
			}
			return gobj;
		}
	}
}
